<template>
  <el-dialog class="sic-open" :visible.sync="visible" width="880px" :title="dataForm.investId?'编辑子投资':'新建子投资'" :close-on-click-modal="false">
    <el-form ref="dataForm" size="mini" :rules="rules" :model="dataForm" label-position="right" label-width="100px">
      <el-row>
        <el-col :span="14">
          <el-form-item label="子投资名称" prop="investName">
            <el-input v-model="dataForm.investName" placeholder="请输入" style="width: 300px;" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="初始净值" prop="initialNetworth">
            <el-input v-model="dataForm.initialNetworth" @change="initialNetworthChange" style="width: 216.66px;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="14">
          <el-form-item label="初始金额" prop="investAmount">
            <el-input v-model="dataForm.investAmount" @change="investAmountChange" :disabled="dataForm.addType==1" placeholder="请输入" style="width: 300px;">
              <template slot="append" style="width: 80px;">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="关联策略" prop="relatedStrategyName">
            <div @click="relatedStrategyHandle">
              <el-input
                size="mini"
                style="width: 216.66px;"
                placeholder="请选择"
                v-model="dataForm.relatedStrategyName"
                readonly>
                <i slot="suffix" class="el-input__icon el-icon-arrow-right"
                :class="realContrastMove?'el-icon-circle-close pointer':'el-icon-arrow-right'"
                @click.stop="clearRelatedStrategy"
                @mouseenter="realContrastMove=true" @mouseleave="realContrastMove=false"></i>
              </el-input>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="14">
          <el-form-item label="初始份额" prop="initialShare">
            <el-input v-model="dataForm.initialShare" @change="initialShareChange" placeholder="请输入" style="width: 300px;">
              <template slot="append" style="width: 80px;">份</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="对标指数" prop="indexId">
            <indexSelectTree :multiple="false" :width="216.66" :indexType.sync="dataForm.indexId" @getIndexName="getIndexNameHandle"></indexSelectTree>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="14">
          <el-form-item label="数据采集方式" prop="">
            <el-select v-model="dataForm.addType" @change="addTypeChange" placeholder="请选择" style="width: 300px;">
              <el-option
                v-for="item in addTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="投资状态" prop="investStatus">
            <el-select v-model="dataForm.investStatus" placeholder="请选择" style="width: 216.66px;">
              <el-option
                v-for="item in statusList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="14">
          <el-form-item prop="mark" label="备注">
            <el-input v-model="dataForm.mark" placeholder="请输入" width="216.66" style="width: 300px;" />
          </el-form-item>
        </el-col>
        <el-col :span="10" v-if="dataForm.investId && isClearNetworthShow">
          <el-form-item
            prop="isClearNetworth"
            label="清空原有净值"
          >
            <el-checkbox v-model="dataForm.isClearNetworth"></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="dataForm.addType==1" class="rh-account">
        <div class="line"></div>
        <div class="rh-title">融航子账号（必填）</div>
        <div class="rh-crad" :class="{'rh-firstCrad': !i, 'rh-lastCrad': i==dataForm.accounts.length-1}" v-for="(item, i) in dataForm.accounts" :key="i">
          <el-row>
            <el-col :span="7">
              <el-form-item :label="`操作账号${i+1}`" label-width="84px" prop="">
                <el-input :class="{border_red: borderRedList.indexOf(i*3)!=-1}" v-model="dataForm.accounts[i].account" placeholder="请输入" style="width: 150px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="初始金额" label-width="75px" prop="">
                <el-input class="initAmountInput" :class="{border_red: borderRedList.indexOf(i*3+1)!=-1}" v-model="dataForm.accounts[i].initAmount" @change="rhInitAmountChange($event, i)" placeholder="请输入" style="width: 190px;">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="投资时间" label-width="75px" prop="">
                <el-date-picker
                 :class="{border_red: borderRedList.indexOf(i*3+2)!=-1}"
                  size="mini"
                  v-model="dataForm.accounts[i].investTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  style="width: 140px;"
                  placeholder="请选择"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <div class="rh-delBtn" @click="delCardHnadle(i)"><i class="iconfont icon-ashbin"></i> 删除</div>
            </el-col>
          </el-row>
        </div>
        <div class="addCard" @click="addCardHnadle"><i class="iconfont icon-add-circle"></i>添加融航子账号</div>
      </div>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false" style="width: 100px;">取 消</el-button>
      <el-button type="primary" @click="addSubmit" style="width: 100px;">确 定</el-button>
    </div>

    <strategyOpen
      v-if="strategyVisible"
      ref="strategyOpen"
      title="选择策略（单选）"
      type="radio"
      :nolink="true"
      :appendToBody="true"
      :userId="userId"
      @selctInvestName="selctInvestNameHandle"
    ></strategyOpen>
  </el-dialog>
</template>

<script>
import indexSelectTree from '@/components/investComn/indexSelectTree.vue'
import { addInvest, uptInvest, queryForUpdate } from '@/api/subInvest'
import { GATHER_OPTIONS, STATUS_OPTIONS } from './const'
import strategyOpen from "@/views/afterManage/afterInvest/relation/strategyOpen.vue";

export default {
  components: { indexSelectTree, strategyOpen },
  props: {
    userId: String | Number
  },
  data() {
    return {
      visible: false,
      dataForm: {
        investName: '',
        initialNetworth: '1',
        investManageType: 2,
        accounts: [{}],
        addType: 2
      },
      isClearNetworthShow: false,
      addTypeList: GATHER_OPTIONS,
      statusList: STATUS_OPTIONS,
      realContrastMove: false,
      strategyVisible: false,

      borderRedList: [],

      rules: {
        investName: [{ required: true, message: '子投资名称必填', trigger: 'change' }],
        investAmount: [{ required: true, message: '初始金额必填', trigger: 'change' }],
        initialShare: [{ required: true, message: '初始份额必填', trigger: 'change' }],
        investStatus: [{ required: true, message: '投资状态必填', trigger: 'change' }],
      }
    }
  },
  methods: {
    init(investId) {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.dataForm = {
          investName: '',
          initialNetworth: '1',
          investManageType: 2,
          accounts: [{}],
          addType: 2
        }
        if(investId) this.queryForUpdate(investId)
      })
    },
    addTypeChange() {
      this.isClearNetworthShow = true
    },
    queryForUpdate(investId) {
      queryForUpdate({ investId }).then(res => {
        this.dataForm = res.body
      })
    },
    getIndexNameHandle(val) {
      this.dataForm.indexName = val
    },
    investAmountChange(val) {
      if(this.dataForm.initialNetworth) {
        const initialShare = val / this.dataForm.initialNetworth
        this.$set(this.dataForm, 'initialShare', initialShare)
      }
    },
    initialNetworthChange(val) {
      if(this.dataForm.investAmount) {
        const initialShare = this.dataForm.investAmount / val
        this.$set(this.dataForm, 'initialShare', initialShare)
      }
    },
    initialShareChange(val) {
      if(this.dataForm.initialNetworth) {
        if(this.dataForm.addType==1&&this.dataForm.investAmount) {
          const initialNetworth = this.dataForm.investAmount / (val)
          this.$set(this.dataForm, 'initialNetworth', initialNetworth)
        }else {
          const investAmount = this.dataForm.initialNetworth * (val)
          this.$set(this.dataForm, 'investAmount', investAmount)
        }
      }
    },
    rhInitAmountChange(e, index) {
      // 转为数值
      if(index!=undefined) {
        const val = this.checkNumber(this.dataForm.accounts[index].initAmount)
        if(val||val==0) {
          this.dataForm.accounts[index].initAmount = val
        }
      }
      this.dataForm.investAmount = 0
      this.dataForm.accounts.forEach(item => {
        const num = item.initAmount ? Number(item.initAmount) : 0
        this.dataForm.investAmount += num
      })
      if(this.dataForm.investAmount==0) {
        this.dataForm.investAmount = null
        this.dataForm.initialShare = null
      }else {
        this.investAmountChange(this.dataForm.investAmount)
      }
    },
    addCardHnadle() {
      this.dataForm.accounts.push({})
    },
    delCardHnadle(i) {
      this.dataForm.accounts.splice(i, 1)
      this.rhInitAmountChange()
    },
    relatedStrategyHandle() {
      this.strategyVisible = true;
      this.$nextTick(() => {
        this.$refs.strategyOpen.init();
      });
    },
    clearRelatedStrategy() {
      this.dataForm.relatedStrategyId = null
      this.dataForm.relatedStrategyName = null
    },
    selctInvestNameHandle(params) {
      this.$set(this.dataForm, 'relatedStrategyId', params.strategyId)
      this.$set(this.dataForm, 'relatedStrategyName', params.strategyName)
    },
    // 过滤非数字
    checkNumber(value) {
      value = value.toString()
      value = value.replace(/[^\d.]/g, '')
      value = value.replace(/^\./g, '')
      value = value.replace(/\.{2,}/g, '.')
      value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      return +value
    },
    addSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          if(this.dataForm.addType==1) {
            this.borderRedList = []
            let tag = 0
            if(!this.dataForm.accounts.length) {
              this.$message({
                message: '融航账号中存在未填项',
                type: 'error'
              })
              return
            }
            this.dataForm.accounts.forEach((item, i) => {
              if(!item.account) {
                tag = 1
                this.borderRedList.push(i*3)
              }
              if(!item.initAmount) {
                tag = 1
                this.borderRedList.push(i*3+1)
              }
              if(!item.investTime) {
                tag = 1
                this.borderRedList.push(i*3+2)
              }
            })
            if(tag) {
              this.$message({
                message: '融航账号中存在未填项',
                type: 'error'
              })
              return
            }
          }
          const apiFun = this.dataForm.investId ? uptInvest : addInvest
          apiFun({
            ...this.dataForm,
            investManageType: 2,
            userId: this.userId
          }).then(res => {
            if(res.code == 0) {
              this.$notify({
                message: res.body,
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.$emit('closeOpen')
            }
          })
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.sic-open {

  ::v-deep .el-dialog { max-height: 800px; overflow-y: auto; }
  ::v-deep .el-dialog__header { border-bottom: 1px solid #F0F0F0; }
  ::v-deep .el-input-group__append { width: 70px; text-align: center; }
  ::v-deep .el-dialog__footer { border-top: 1px solid #F0F0F0; padding: 16px 20px; }
  // ::v-deep .el-dialog__body {
  //   max-height: 600px; overflow-y: auto;
  //   // 全局默认滚动条
  //   &::-webkit-scrollbar {
  //     /*滚动条整体样式*/
  //     width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
  //     height: 1px;
  //     border-radius: 2px;
  //   }
  //   &::-webkit-scrollbar-thumb {
  //     /*滚动条里面小方块*/
  //     border-radius: 10px;
  //     box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);
  //     background: rgba(0, 0, 0, 0.1);
  //   }
  //   &::-webkit-scrollbar-track {
  //     /*滚动条里面轨道*/
  //     box-shadow: inset 0 0 5px rgba(87, 175, 187, 0.1);
  //     border-radius: 10px;
  //     background: #ededed;
  //   }
  // }

  ::v-deep .el-input.is-disabled {
    .el-input-group__append {
      border-left: 1px solid #DCDFE6;
    }
  }

  .line { height: 1px; border-top: 1px solid #F0F0F0; }
  .rh-account {
    .rh-title {
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: rgba(0,0,0,0.7500);
      line-height: 24px;
      margin: 15px 0 12px;
    }
    .rh-crad {
      background: #F5F5F5;
      padding: 9px 15px;
      ::v-deep .el-form-item { margin-bottom: 0; }
      .rh-delBtn {
        width: 60px;
        line-height: 28px;
        background: #FFF;
        cursor: pointer;
        padding: 0 2px;
        text-align: center;
        float: right;
      }
    }
    .rh-firstCrad { border-top-left-radius: 5px; border-top-right-radius: 5px; }
    .rh-lastCrad { border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; }
    .addCard {
      height: 40px;
      margin-top: 16px;
      border-radius: 5px;
      border: 1px solid #EBEBEB;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #666666;
      cursor: pointer;
      .iconfont { font-size: 20px; margin-right: 5px; }
      &:hover {
        color: #409EFF;
        border-color: #c6e2ff;
        background-color: #ecf5ff;
      }
    }
  }

  ::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
    border-radius: 2px;
  }
  ::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);
    background: rgba(0, 0, 0, 0.1);
  }
  ::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(87, 175, 187, 0.1);
    border-radius: 10px;
    background: #ededed;
  }
  .initAmountInput {
    ::v-deep .el-input-group__append { padding: 0 10px; width: 50px; }
  }
}
</style>


